#include "mainwindow.h"
#include "ui_mainwindow.h"

#include <QDir>
#include <QFile>
#include <QFileDialog>

#include "log/loghandle.h"
#include "json/jsonhandle.h"
#include "ffopt/ffopthandle.h"
#include "config/cfghandle.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    uiInit();

    connect(ui->pbtnChooseFile, &QPushButton::clicked, [=] {
        QString file_path = QFileDialog::getOpenFileName(this,
                                                         "选择JSON文件",
                                                         QDir::currentPath(),
                                                         "所有文件(*.*);;JSON文件(*.json);;");
        if(file_path != "") {
            ui->leditJsonFile->setText(file_path);
        }
    });

    connect(ui->pbtnChooseFolder, &QPushButton::clicked, [=] {
        QString folder_path = QFileDialog::getExistingDirectory(this,
                                                                "选择文件夹",
                                                                QDir::currentPath());
        if(folder_path != "") {
            ui->leditGenFolder->setText(folder_path);
        }
    });

    connect(ui->pbtnCreate, &QPushButton::clicked, [=] {
        l_status->setText(" 生成中...");
        LogHandle(ui->peditLog).print("STM32 quick engine started!");

        LogHandle(ui->peditLog).print("使用配置文件：");
        LogHandle(ui->peditLog).print(ui->leditJsonFile->text());
        LogHandle(ui->peditLog).print("工程生成位置：");
        LogHandle(ui->peditLog).print(ui->leditGenFolder->text());

        bool res = 0;
        JsonHandle json_handle(ui->peditLog);
        res = json_handle.jsonScan(ui->leditJsonFile->text(), ui->leditGenFolder->text());

        if(res) {
            FFOptHandle ffopt(ui->peditLog);
            ffopt.generateFolder(json_handle.getFolderTree());
            ffopt.generateFile(json_handle.getFileTree());
            ffopt.copyFile(json_handle.getFileCTree());
            ffopt.copyFolder(json_handle.getFolderCTree());

            CfgHandle cfg_handle;
            cfg_handle.init("config.ini");
            cfg_handle.update("file/default_gen", ui->leditGenFolder->text());
        }

        LogHandle(ui->peditLog).print("STM32 quick engine finished!");
        l_status->setText(" 完毕");
    });
}

MainWindow::~MainWindow() {
    delete ui;
}

void MainWindow::uiInit() {
    setWindowTitle("QuickEngine");

    CfgHandle cfg_handle;
    cfg_handle.init("config.ini");
    QMap<QString, QVariant> file_cfg_map = cfg_handle.load("file");

    QString file_name = file_cfg_map.value("default_name", "test.json").toString();
    ui->leditJsonFile->setText(QString("%1/%2").arg(QDir::currentPath(), file_name));

    QString gen_path = file_cfg_map.value("default_gen", QDir::currentPath()).toString();
    ui->leditGenFolder->setText(gen_path);

    menuInit();

    l_status = new QLabel(" 完毕");

    ui -> statusBar->addWidget(l_status);
    ui -> statusBar -> addPermanentWidget(new QLabel(tr(" Copyright © 2024-2042 混子还在路上 版权所有")));
    ui -> statusBar -> setStyleSheet(QString("QStatusBar::item {border: 0}"));
}

void MainWindow::menuInit() {
    QMenu *opt_menu = new QMenu(QStringLiteral("选项(&O)"), this);
    QMenu *cfg_menu = new QMenu(QStringLiteral("设置(&C)"), this);
    QMenu *help_menu = new QMenu(QStringLiteral("帮助(&H)"), this);

    QAction *opt_quit = new QAction(QStringLiteral("退出(&Q)"), this);

    ui -> menuBar -> addMenu(opt_menu);
    ui -> menuBar -> addMenu(cfg_menu);
    ui -> menuBar -> addMenu(help_menu);

    opt_quit -> setShortcut(Qt::CTRL | Qt::Key_Q);
    opt_menu -> addAction(opt_quit);

    connect(opt_quit, &QAction::triggered, this, &QMainWindow::close);
}

void MainWindow::resetPTextMenu() {
    ui->peditLog->setContextMenuPolicy(Qt::CustomContextMenu);

    QMenu *ptt_menu = new QMenu(ui->peditLog);

    QAction *copy_ac = new QAction("复制", ptt_menu);
    copy_ac->setShortcut(QKeySequence::Copy);
    copy_ac->setShortcutContext(Qt::WidgetShortcut);

    QAction *select_all_ac = new QAction("全部选中", ptt_menu);
    select_all_ac->setShortcut(QKeySequence::SelectAll);
    select_all_ac->setShortcutContext(Qt::WidgetShortcut);

    QAction *clear_ac = new QAction("全部清除", ptt_menu);

    //将菜单选项添加至菜单上
    ptt_menu->addAction(copy_ac);
    ptt_menu->addSeparator();
    ptt_menu->addAction(select_all_ac);
    ptt_menu->addAction(clear_ac);

    //使用卡槽信号，使功能和菜单选项产生关联
    connect(copy_ac, &QAction::triggered, ui->peditLog, &QPlainTextEdit::copy);
    connect(select_all_ac, &QAction::triggered, ui->peditLog, &QPlainTextEdit::selectAll);
    connect(clear_ac, &QAction::triggered, ui->peditLog, &QPlainTextEdit::clear);

    //使用卡槽信号，使菜单和文本域产生关联
    connect(ui->peditLog, &QPlainTextEdit::customContextMenuRequested, [=] {
        //根据选中情况决定是否启用复制功能
        copy_ac->setDisabled(ui->peditLog->textCursor().selectedText().isEmpty());
        //将菜单移动至鼠标标处，并显示菜单
        ptt_menu->move(cursor().pos());
        ptt_menu->show();
    });
}
